<?php

namespace app\middleware;

use app\model\setting\TraceIDSetting;
use Monolog\Handler\LogEntriesHandler;
use Monolog\Logger;
use support\Log;
use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class ResponseMiddlewafe implements MiddlewareInterface
{
    public function process(Request $request, callable $handler): Response
    {
        //echo '这里是请求穿越阶段，也就是请求处理前';


        Log::info("============ TRACEID " . TraceIDSetting::instance()->getTraceID() . " ==============");
        Log::info("URL: " . "{$request->method()} 请求: {$request->url()}");
        Log::info('REFERER: ' . ($_SERVER['HTTP_REFERER'] ?? 'NO REFERER'));
        Log::info('GET: ' . json_encode($_GET, JSON_UNESCAPED_UNICODE));
        Log::info('POST: ' . json_encode($_POST, JSON_UNESCAPED_UNICODE));
        Log::info('COOKIE: ' . json_encode($_COOKIE, JSON_UNESCAPED_UNICODE));
        Log::info('PARAM: ' . json_encode(input('param.'), JSON_UNESCAPED_UNICODE));
        Log::info('- - - - - - - - - - - - - -');
        /**
         * @var Response $response
         */
        $response = $handler($request); // 继续向洋葱芯穿越，直至执行控制器得到响应

        //写日志，截取前1000个中文字符串
        $body = mb_substr($response->rawBody(), 0, 1000, 'utf-8');

        Log::log("debug", "Response: {$body}");
        TraceIDSetting::instance()->update();

        return $response;

    }
}